package org.jeecg.common.rc;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * mybatisplus 自动填充处理器
 *
 * @author addzero
 * @see MetaObjectHandler
 * @since 2022/10/14
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        autoFill(metaObject, inertMap);
    }

    static HashMap<String, Object> inertMap = new HashMap<String, Object>() {{
        put("createTime", LocalDateTime.now());
        put("updateTime", LocalDateTime.now());
        //put("deleted", 0);
        //createBy
        //put("createTime", LocalDateTime.now());

    }};

    static HashMap<String, Object> updateMap = new HashMap<String, Object>() {{
        //put("createTime", LocalDateTime.now());
        put("updateTime", LocalDateTime.now());
        //put("createTime", LocalDateTime.now());

    }};

    private void autoFill(MetaObject metaObject, final HashMap<String, Object> map) {
        map.forEach((k, v) -> {
            if (metaObject.hasSetter(k)) {
                this.setFieldValByName(k, v, metaObject);
            }
        });

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        autoFill(metaObject, updateMap);

    }
}
